package tk.mybatis.springboot.conf;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/21.
 */
@Component
@Slf4j
@Data
public class SocketHandlerComponent extends TextWebSocketHandler {

    private Map<String,WebSocketSession> sessionMap = new HashMap<>();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        //payLoad可以是任意字符
        log.info(message.getPayload());
        String userId = (String) session.getAttributes().get("userId");
        //目前不支持多客户端socket
        /*if(!StringUtils.isEmpty(userId)){
            WebSocketSession webSocketSession = sessionMap.get(userId);
            if(null != webSocketSession && webSocketSession.isOpen()){
                webSocketSession.close();
            }
        }*/
        sessionMap.put(userId,session);
    }
}
